package cn.tedu.rpc;


import com.rabbitmq.client.*;
import com.rabbitmq.client.AMQP.BasicProperties;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Server {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.通过连接工厂配置rabbitmq的连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1");
        cf.setPort(5672); //客户端端口，5672是默认端口，可以省略
        cf.setUsername("guest");
        cf.setPassword("guest");
        //2.创建tcp和channel
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        //3.服务器需要从调用队列中获取调用信息
        cc.queueDeclare("rpc_queue",false,false,false,null);
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                //从delivery对象中取出n
                String msg = new String(delivery.getBody());
                //获取返回队列的队列名
                String replyTo = delivery.getProperties().getReplyTo();
                //获取关联ID
                String cid = delivery.getProperties().getCorrelationId();
                BasicProperties properties = new BasicProperties().builder().correlationId(cid).build();
                int n = Integer.parseInt(msg);
                long fbnqs = fbnqs(n);
                //把计算结果发送到返回队列，需要携带关联ID
                cc.basicPublish("",replyTo,properties,(fbnqs+"").getBytes());
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        //4.从调用队列中去消息数据
        cc.basicConsume("rpc_queue",true,deliverCallback,cancelCallback);
    }
    //服务：就收一个整数值n，求第n个斐波那契数
    static long fbnqs(int n){
        //递归必须有结束条件
        if(n==1 || n==2)
            return 1;
        return fbnqs(n-1)+fbnqs(n-2);
    }
}
